﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GMS.MainClasses;
using GMS.ServiceFunctions.Data;
using GMS.ServiceFunctions.FunctionForControls;
using GMS.MainForm;

namespace GMS.UsersGroups
{
    public partial class UsersGroups : ChildForms
    {
        BindingSource bsGroups = new BindingSource();
        BindingSource bsUsers = new BindingSource();
        BindingSource bsGroupsUsers = new BindingSource();
        FunctionsForDataGridView FFDGV = new FunctionsForDataGridView();
        private Int32 VIdGroup, VIdUser;

        public UsersGroups()
        {
            InitializeComponent();
            StoredProcedures = new String[6];

            StoredProcedures[0] = "[SelectGroups]";
            StoredProcedures[1] = "[SelectUsers]";
            StoredProcedures[2] = "[SelectUsersGroups]";
            StoredProcedures[3] = "[AddUserToGroup]";
            StoredProcedures[4] = "[DeleteLinkUserGroup]";
            StoredProcedures[5] = "[CloneGroup]";
        }
        private void RefreshGrid()
        {
            bsGroups.DataSource = MRF.ReturnDataSetDB(ConnectionString, StoredProcedures[0]);
            bsGroups.DataMember = "table";

            bsUsers.DataSource = MRF.ReturnDataSetDB(ConnectionString, StoredProcedures[1]);
            bsUsers.DataMember = "table";

            bsGroupsUsers.DataSource = MRF.ReturnDataSetDB(ConnectionString, StoredProcedures[2]);
            bsGroupsUsers.DataMember = "table";

            dataGridView1.DataSource = bsGroups;
            dataGridView3.DataSource = bsUsers;
            dataGridView2.DataSource = bsGroupsUsers;
        }
        private void UsersGroups_Load(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                VIdGroup = Convert.ToInt32(dataGridView1.CurrentRow.Cells["IdGroup"].Value);
                bsGroupsUsers.Filter = "IGroup = " + VIdGroup;
                FFDGV.TextForGroupBox(groupBox1, dataGridView1, "Группы         ");
            }
            catch { }
        }

        private void dataGridView3_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            try
            {
                FFDGV.PaintGridRows(dataGridView3, e, dataGridView3.Columns["UserStatus"].Index, -1, System.Drawing.Color.Red);
            }
            catch { }
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            try
            {
                FFDGV.PaintGridRows(dataGridView1, e, dataGridView1.Columns["GroupStatus"].Index, -1, System.Drawing.Color.Red);
            }
            catch { }
        }

        private void AddUserToGroupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (Convert.ToInt32(dataGridView3.CurrentRow.Cells["UserStatus"].Value) != 1)
                {
                    MessageBox.Show("Пользователь деактивирован!!! Привязка не возможна!!!", "Ошибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (Convert.ToInt32(dataGridView1.CurrentRow.Cells["GroupStatus"].Value) != 1)
                {
                    MessageBox.Show("Группа деактивирована!!! Привязка не возможна!!!", "Ошибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (MessageBox.Show("Делаем связку: " + dataGridView1.CurrentRow.Cells["Название группы"].Value.ToString() + " + " + dataGridView3.CurrentRow.Cells["Login"].Value.ToString(), "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    MRF.ExecuteSqlCommand(StoredProcedures[3] + " " + VIdUser + ", " + VIdGroup, ConnectionString);
                    RefreshGrid();
                }
                    
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Ошибка!!!",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

        private void dataGridView3_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                VIdUser = Convert.ToInt32(dataGridView3.CurrentRow.Cells["IdUser"].Value);
                bsGroupsUsers.Filter = "IUser = " + VIdUser;
                FFDGV.TextForGroupBox(groupBox3, dataGridView3, "Пользователи       ");
            }
            catch { }
        }

        private void DeleteLinkToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Разрываем связку: " + dataGridView2.CurrentRow.Cells["Логин"].Value.ToString() + " + " + dataGridView2.CurrentRow.Cells["Название группы"].Value.ToString(), "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    MRF.ExecuteSqlCommand(StoredProcedures[4] + " " + Convert.ToInt32(dataGridView2.CurrentRow.Cells["IUser"].Value) + ", " + Convert.ToInt32(dataGridView2.CurrentRow.Cells["IGroup"].Value), ConnectionString);
                    RefreshGrid();
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.ToString(), "Ошибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); }
        }

        private void AddGroupToUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddUserToGroupToolStripMenuItem_Click(sender, e);
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            AddUserToGroupToolStripMenuItem_Click(sender, e);
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            AddUserToGroupToolStripMenuItem_Click(sender, e);
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            DeleteLinkToolStripMenuItem_Click(sender, e);
        }

        private void dataGridView2_SelectionChanged(object sender, EventArgs e)
        {
            FFDGV.TextForGroupBox(groupBox2, dataGridView2, "Группы/Пользователи        ");
        }

        private void CloneGroupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.SelectedRows.Count < 2)
                    MessageBox.Show("Нельзя клонировать группу саму в себя!!!", "Ошибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                {
                    if (MessageBox.Show("Клонируем - " + dataGridView1.SelectedRows[dataGridView1.SelectedRows.Count - 1].Cells[""].Value.ToString() + ", получаем - " + dataGridView1.SelectedRows[0].Cells["Название группы"].Value.ToString() + "?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        MRF.ExecuteSqlCommand(StoredProcedures[5] + " " + dataGridView1.SelectedRows[dataGridView1.SelectedRows.Count - 1].Cells["IdGroup"].Value.ToString() + ", " + dataGridView1.SelectedRows[0].Cells["IdGroup"].Value.ToString(), ConnectionString);
                        RefreshGrid();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Ошибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            CloneGroupToolStripMenuItem_Click(sender, e);
        }

        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            bsGroups.Filter = "[Название группы] like '%"+textBox1.Text.Trim()+"%'";
        }

        private void textBox2_KeyUp(object sender, KeyEventArgs e)
        {
            bsUsers.Filter = "Login like '%" + textBox2.Text.Trim() + "%'";
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            AboutUsersGroups AUG = new AboutUsersGroups();
            AUG.Show();
        }

    }
}
